package de.recipeminer.persistence;

import com.db4o.ObjectSet;
import org.apache.log4j.Logger;

/**
 * @author Markus Ackermann
 */
public class Db4oSingletonHelper {
    private static Logger logger = Logger.getLogger(Db4oSingletonHelper.class);

    public static <T> T getPersistedInstance(Class<T> class_) {
        Db4oContainer container = Db4oContainers.getDefault();
        ObjectSet<T> objects = container.query(class_);
        if(objects.size() == 0)
            return null;
        else if (objects.size() > 1)
            throw new IllegalStateException(String.format("Several instancs of %s-Singleton " +
                    "found in database.", class_.getName()));
        else {
            logger.info("Retrieved " + class_.getName() + " instance from Db4o.");
            return objects.next();
        }
    }
}
